import { Node,BlockInputEvents,Widget,Layers, instantiate } from "cc"
import { ViewUtil } from "../../utils/ViewUtil";
import { Notify } from "../prompt/Notify";

const WatiPrefabPath = "common/prefab/wait";
const NotifyPrefabPath ="common/prefab/notify"

export class LayerNotify extends Node{
    /** 防止点击穿透 */
    private black!:BlockInputEvents;
    /**等待Node */
    private wait:Node = null!;
    /**弹窗 */
    private notify:Node = null!;
    /**弹窗内容 */
    private notifyItem:Node = null!;


    constructor(name:string){
        super(name)
        const widget:Widget = this.addComponent(Widget)
        widget.isAlignLeft = widget.isAlignRight = widget.isAlignTop = widget.isAlignBottom = true;
        widget.left = widget.right = widget.top  = widget.bottom = 0
        widget.alignMode = 2;
        widget.enabled = true;
        this.init();
    }

    private init():void{
        this.layer =Layers.Enum.UI_2D;
        this.black = this.addComponent(BlockInputEvents);
        this.black.enabled = false;
    }

    /**
     * 打开等待等待
     */
    public waitOpen():void{
        if (this.wait == null) {
            this.wait = ViewUtil.createPrefabNode(WatiPrefabPath);
        }
        if (this.wait.parent == null) {
            this.wait.parent  = this;
            this.black.enabled = true;
        }
    }

    /**
     * 关闭等待
     */
    public waitClose():void{
        if (this.wait  && this.wait.parent) {
            this.wait.parent = null;
            this.black.enabled = false;
        }
    }

    /**
     * 向界面添加Toast消息
     * @param msg 
     * @param userI18n 
     */
    public toast(msg:string,userI18n:boolean):void{
        if (this.notify == null) {
            this.notify = ViewUtil.createPrefabNode(NotifyPrefabPath);
            this.notifyItem = this.notify.children[0];
            this.notifyItem.parent = null;
        }
        this.notify.parent  = this;
        let childNode = instantiate(this.notifyItem);
        let prompt = childNode.getChildByName("prompt");
        let toastCom = prompt.getComponent(Notify);
        childNode.parent = this.notify;
        toastCom.onCompleted = ()=>{
            if (this.notify.children.length == 0) {
                this.notify.parent = null;
            }
        }
        toastCom.toast(msg,userI18n);

        if(this.notify.children.length > 3){
            this.notify.children[0].destroy();
        }
        
    }


}